import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header


def send_email_with_attachment(sender, password, receiver, subject, body, attachment_path):
    # 设置SMTP服务器地址和端口
    smtp_server = "smtp.163.com"
    smtp_port = 465

    # 创建MIMEMultipart对象，设置邮件内容和编码
    message = MIMEMultipart()
    message["From"] = Header(sender, "utf-8")
    message["To"] = Header(receiver, "utf-8")
    message["Subject"] = Header(subject, "utf-8")

    # 添加邮件正文
    message.attach(MIMEText(body, "plain", "utf-8"))

    # 读取附件内容
    with open(attachment_path, "rb") as f:
        attachment = MIMEApplication(f.read())
        attachment.add_header("Content-Disposition", "attachment", filename=("gbk", "", attachment_path.split("/")[-1]))
        message.attach(attachment)

    try:
        # 连接SMTP服务器
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(sender, password)
        server.sendmail(sender, [receiver], message.as_string())
        server.quit()
        return "邮件发送成功！"
    except Exception as e:
        return f"邮件发送失败：{e}"


# 示例使用
sender = "you-email@xxx.com"  # 发送者邮箱
password = "you-email-password"  # 发送者邮箱密码或授权码
receiver = "xxxxxxxxx@qq.com"  # 接收者邮箱
subject = "测试邮件"  # 邮件主题
body = "这是一封来自Python脚本的测试邮件，包含附件。"  # 邮件正文
attachment_path = "../a.txt"  # 附件路径

# 调用函数发送邮件
# send_email_with_attachment(sender, password, receiver, subject, body, attachment_path)
# 由于我不能提供真实的邮箱账号和密码，这里只是展示函数，实际发送需要您自己调用并提供正确的账号信息。
print(send_email_with_attachment(sender, password, receiver, subject, body, attachment_path))
